﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using CommonTagTime;
using CommonTagTime.Business;
using CommonTagTime.ModelObject;
using System.Xml.Linq;
using System.IO;
public partial class ShopRegister : SitePage
{
    #region Init,Load
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        InitData();
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {          
            LoadCountryData();
            SetDefaultData();            
        }
    }
    #endregion

    #region Method
    private void LoadStateByCountry()
    {
        ddlState.Items.Clear();
        if (ddCountry.SelectedValue == clsConfigData.DEFAULT_CUSTOMER_US_COUNTRY_CODE)
        {
            busState objBus = new busState();
            StateCollection lstState = objBus.GetByCountry(ddCountry.SelectedValue);
            ddlState.DataSource = lstState;
            ddlState.DataTextField = busState.STATENAME;
            ddlState.DataValueField = busState.STATECODE;
            ddlState.DataBind();
        }
        ddlState.Items.Insert(0, new ListItem("- - -", ""));
    }
    private void InitData()
    {
        string validateGroup = "customer";
        vsumCustomer.ValidationGroup = reqCountry.ValidationGroup = btnSubmit.ValidationGroup = reqCompanyName.ValidationGroup = validateGroup;
        reqAddress1.ValidationGroup = reqCity.ValidationGroup = reqConfirmEmail.ValidationGroup = reqContactName.ValidationGroup = validateGroup;
        reqEmail.ValidationGroup = reqPhone.ValidationGroup = reqPostalCode.ValidationGroup = reqProvince.ValidationGroup = reqState.ValidationGroup = validateGroup;
        cusEmail.ValidationGroup = cusPhone.ValidationGroup = cusPostalCode.ValidationGroup = cmpConfirmEmail.ValidationGroup = validateGroup;
        //Init message
        reqCountry.ErrorMessage = string.Format(Resources.Resource.MSG_REQUIREMENT, "Country");
        reqCompanyName.ErrorMessage = string.Format(Resources.Resource.MSG_REQUIREMENT, "Company name");
        reqContactName.ErrorMessage = string.Format(Resources.Resource.MSG_REQUIREMENT, "Contact name");
        reqAddress1.ErrorMessage = string.Format(Resources.Resource.MSG_REQUIREMENT, "Address1");
        reqCity.ErrorMessage = string.Format(Resources.Resource.MSG_REQUIREMENT, "City");
        reqState.ErrorMessage = string.Format(Resources.Resource.MSG_REQUIREMENT, "State");
        reqPostalCode.ErrorMessage = string.Format(Resources.Resource.MSG_REQUIREMENT, "Zip/ Postal Code");
        reqProvince.ErrorMessage = string.Format(Resources.Resource.MSG_REQUIREMENT, "Province/Region");
        reqPhone.ErrorMessage = string.Format(Resources.Resource.MSG_REQUIREMENT, "Phone");
        reqEmail.ErrorMessage = string.Format(Resources.Resource.MSG_REQUIREMENT, "Email");
        reqConfirmEmail.ErrorMessage = string.Format(Resources.Resource.MSG_REQUIREMENT, "Confirm Email");
        cusEmail.ErrorMessage = string.Format(Resources.Resource.MSG_VALID, "Email");
        cmpConfirmEmail.ErrorMessage = string.Format(Resources.Resource.MSG_VALID, "Confirm Email");
        cusPhone.ErrorMessage = string.Format(Resources.Resource.MSG_VALID, "Phone");
        cusPostalCode.ErrorMessage = string.Format(Resources.Resource.MSG_VALID, "Zip/ Postal Code");
        this.Page.Header.Title = string.Format(Resources.Resource.TITLE, "Become a Distributor");
    }
    private void SetDefaultData()
    {
        string countryCode = clsQueryString.GetString("c");
        if (countryCode == clsConfigData.DEFAULT_CUSTOMER_US_COUNTRY_CODE)//customer in US
        {
            ddCountry.SelectedValue = countryCode;
            trCountry.Visible = false;
            reqCountry.Visible = false;
            trProvince.Visible = false;
            reqProvince.Visible = false;
            reqPostalCode.Visible = true;
            cusPostalCode.Visible = true;
            lblZipCode.Text += " <span class='commentRequireInputText'>*</span>";
        }
        else//international customer
        {
            ddCountry.SelectedValue = string.Empty;
            trState.Visible = false;
            reqState.Visible = false;
            reqPostalCode.Visible = false;
            cusPostalCode.Visible = false;

        }
        lblZipCode.Text += ":";
    }
    private void LoadCountryData()
    {
        busCountry objBus = new busCountry();
        string countryCode = clsQueryString.GetString("c");
        ddCountry.Items.Clear();
        if (countryCode == clsConfigData.DEFAULT_CUSTOMER_US_COUNTRY_CODE)//customer in US
        {
            ddCountry.Items.Add(new ListItem(clsConfigData.DEFAULT_CUSTOMER_US_COUNTRY_CODE, clsConfigData.DEFAULT_CUSTOMER_US_COUNTRY_CODE));
            //Load State data
            LoadStateByCountry();
        }
        else
        {
            CountryCollection lstCountry = objBus.GetAll();
            foreach (Country objCountry in lstCountry)
            {
                if (objCountry.CountryCode != clsConfigData.DEFAULT_CUSTOMER_US_COUNTRY_CODE)//international  customer
                {
                    ddCountry.Items.Add(new ListItem(objCountry.CountryName, objCountry.CountryCode));
                }
            }
        }
        ddCountry.Items.Insert(0, new ListItem("- - -", ""));
    }
    #endregion

    #region Events
    protected void ddCountry_SelectedIndexChanged(object sender, EventArgs e)
    {
        LoadStateByCountry();
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            CommonTagTime.ModelObject.Distributor objDistributor = new CommonTagTime.ModelObject.Distributor();
            objDistributor.Address1 = txtAddress1.Text.Trim();
            objDistributor.Address2 = txtAddress2.Text.Trim();
            objDistributor.City = txtCity.Text.Trim();
            objDistributor.CompanyName = txtCompanyName.Text.Trim();
            objDistributor.ContactName = txtContactName.Text.Trim();
            objDistributor.CountryCode = ddCountry.SelectedValue;
            objDistributor.Email = txtEmail.Text.Trim();
            objDistributor.Fax = txtFax.Text.Trim();
            objDistributor.IsActive = false;
            objDistributor.Note = txtComment.Text.Trim();
            objDistributor.Phone = txtPhone.Text.Trim();      
            objDistributor.ZipCode = txtPostalCode.Text.Trim();
            if (ddCountry.SelectedValue == clsConfigData.DEFAULT_CUSTOMER_US_COUNTRY_CODE)//customer in US
            {
                objDistributor.StateCode = ddlState.SelectedValue;
                objDistributor.Province = string.Empty;
            }
            else
            {
                objDistributor.StateCode = string.Empty;
                objDistributor.Province = txtProvince.Text;
            }
            busDistributor objBus = new busDistributor();
            if (objBus.Insert(objDistributor))
            {
                //Send mail to Admin
                //Send mail to Customer                             
                SendMailToClient(clsConfigData.DEFAULT_MAIL_SERVER,clsConfigData.DEFAULT_MAIL_FROM,clsConfigData.DEFAULT_MAIL_TIMEOUT);
                SendMailToAdmin(clsConfigData.DEFAULT_MAIL_SERVER, clsConfigData.DEFAULT_MAIL_FROM, clsConfigData.DEFAULT_MAIL_TIMEOUT);
                Response.Redirect(ConfigurationManager.AppSettings["thankyouUrl"].ToString());
            }
            else
            {
                lblErrorMessage.Text = Resources.Resource.MSG_INSERT_DISTRIBUTOR_ERROR;
            }
        }
    }
    public bool SendMailToClient(string mailServer,string sender,int timeout)
    {
        string path = Server.MapPath("~/" + clsConfigData.DEFAULT_MAIL_TEMPLATE_REGISTER_DISTRIBUTOR_CUSTOMER);
        string[] template = ReadFile(path);
        clsEmail mail = new clsEmail();
        mail.Sender =sender;
        mail.Receiver = txtEmail.Text;
        mail.Body =string.Format(template[1],txtContactName.Text.Trim(),txtCompanyName.Text,txtEmail.Text.Trim(),txtAddress1.Text.Trim());
        mail.Subject = template[0];
        mail.BodyFormat = enmBodyFormat.HTML;
        mail.TimeOut = timeout;
        return mail.SendExchangeMail();
    }
    public bool SendMailToAdmin(string mailServer,string sender,int timeout)
    {
        string path = Server.MapPath("~/" + clsConfigData.DEFAULT_MAIL_TEMPLATE_REGISTER_DISTRIBUTOR_ADMIN);
        string[] template = ReadFile(path);
        clsEmail mail = new clsEmail();
        mail.Sender = sender;
        mail.Receiver = sender;
        mail.Body = string.Format(template[1],txtCompanyName.Text,txtContactName.Text.Trim(), txtEmail.Text.Trim(), txtAddress1.Text.Trim());
        mail.Subject = template[0];
        mail.BodyFormat = enmBodyFormat.HTML;
        mail.TimeOut = timeout;
        return mail.SendExchangeMail();
    }
    public string[] ReadFile(string path)
    {
        string title = string.Empty;
        string body = string.Empty;
        string[] lines = File.ReadAllLines(path);
        for(int i=0;i<lines.Length;i++)
        {
            if (i == 0)
                title = lines[i].ToString();
            else
            {
                body += lines[i].ToString() + "\r\n";
            }
        }
        string[] result = new string[2];
        result[0] =title;
        result[1] =body;
        return result;
    }
    #endregion

    #region Validate Data
    protected void CheckSZipCode(object source, ServerValidateEventArgs args)
    {
        args.IsValid = clsValidate.CheckPostalCodeValid(args.Value);
    }
    protected void CheckSPhone(object source, ServerValidateEventArgs args)
    {
        args.IsValid = clsValidate.CheckPhoneValid(args.Value);
    }
    protected void CheckSEmail(object source, ServerValidateEventArgs args)
    {
        args.IsValid = clsValidate.CheckEmailValid(args.Value);
    }
    #endregion
   
}